package com.biz.primus.ms.auth.service;

import com.biz.primus.base.enums.CommonStatus;
import com.biz.primus.base.exception.BizBusinessException;
import com.biz.primus.ms.auth.dao.po.Role;
import com.biz.primus.ms.auth.dao.po.User;
import com.biz.primus.ms.auth.dao.repository.RoleRepository;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class RoleService {
    private static final Logger logger = LoggerFactory.getLogger(RoleService.class);

    private final RoleRepository roleRepository;

    @Autowired
    public RoleService(RoleRepository roleRepository) {
        this.roleRepository = roleRepository;
    }

    public Role getRole(Long id) {
        return roleRepository.findOne(id);
    }

    public void delete(Long id) {
        roleRepository.updateStatus(id, CommonStatus.DISABLE);
    }

    public void addOrUpdate(Role role) {
        Role resRole = null;
        if(role.getId() != null){
            resRole = roleRepository.findOne(role.getId());
        }
        if (resRole != null && resRole.getOrderIndex() != null) {
            role.setOrderIndex(resRole.getOrderIndex());
        }
        roleRepository.save(role);
    }

    public List<Role> findByStatus(CommonStatus status) {
        return roleRepository.findByStatus(status);
    }

    /**
     * 用于判定：在修改或添加角色名称时,数据库是否是该角色名称
     * 存在则返回false,否则返回true
     */
    public Boolean isExist(Role param) {

        Role role = roleRepository.findByNameAndStatus(param.getName(), CommonStatus.ENABLE);
        if (role != null) {
            if (param.getId() != null && param.getId().equals(role.getId())) {
                return Boolean.FALSE;
            }
            return Boolean.TRUE;
        }
        return Boolean.FALSE;
    }

    public Role newRole(User user, Role role) throws BizBusinessException {
        Role resRole = roleRepository.findByNameAndStatus(role.getName(), CommonStatus.ENABLE);
        if (resRole != null) {
            logger.error("创建角色名称已经存在 name:{}", role.getName());
            throw new BizBusinessException("创建名称已经存在");
        }
        return roleRepository.save(role);
    }

    public Role updateRole(Role role) {
        return roleRepository.save(role);
    }




}